package com.fc.utils;

import com.fc.exception.BusinessException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.SignatureException;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.Map;

public class JwtUtil {

    public static String createJwt(SignatureAlgorithm sign, String secret, Map<String, Object> map, Long expiration) {
        String jwt = Jwts.builder()
                .signWith(sign, secret)
                .setClaims(map)
                .setExpiration(new Date(System.currentTimeMillis() + expiration))
                .compact();
        return jwt;
    }

    public static Claims parserJwt(String secret, String jwt) {
        if (!StringUtils.hasText(jwt)) {
            throw new BusinessException(401, "Unauthorized");
        }
        // 解析失败就会报异常，利用try catch判断解析是否成功
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(jwt)
                    .getBody();
            return claims;
        } catch (SignatureException e) {
            throw new BusinessException(401, e.getMessage());
        }
    }
}